import 'dart:convert';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:http/http.dart' as http;

class UploadService {
  static const String baseUrl = 'http://192.168.101.13:8080'; // 按需修改
  final ImagePicker _picker = ImagePicker();

  Future<File?> pickImage() async {
    final XFile? xfile = await _picker.pickImage(source: ImageSource.gallery);
    if (xfile == null) return null;
    return File(xfile.path);
  }

  Future<List<File>> pickImages({int? maxImages}) async {
    final List<XFile> xfiles = await _picker.pickMultiImage(
      imageQuality: 85,
      maxWidth: 1800,
      maxHeight: 1800,
    );
    if (xfiles.isEmpty) return [];
    final files = xfiles.map((x) => File(x.path)).toList();
    if (maxImages != null && files.length > maxImages) {
      return files.sublist(0, maxImages);
    }
    return files;
  }

  Future<String> uploadImage(File file) async {
    final uri = Uri.parse('$baseUrl/files/upload');
    final request = http.MultipartRequest('POST', uri)
      ..files.add(await http.MultipartFile.fromPath('file', file.path));

    final streamed = await request.send();
    final resp = await http.Response.fromStream(streamed);
    if (resp.statusCode != 200) {
      throw Exception('上传失败 HTTP ${resp.statusCode}');
    }

    final body = resp.body.trim();
    if (body.startsWith('{')) {
      final map = jsonDecode(body) as Map<String, dynamic>;
      final code = map['code'];
      if (code is int && (code == 200 || code == 1 || code == 0)) {
        final data = map['data'];
        if (data is String && data.isNotEmpty) return data;
      }
      throw Exception(map['msg']?.toString() ?? '上传失败');
    }
    return body; // 纯字符串
  }

  Future<List<String>> uploadImages(List<File> files) async {
    final List<String> urls = [];
    for (final f in files) {
      final url = await uploadImage(f);
      urls.add(url);
    }
    return urls;
  }
}
